import React, { PureComponent } from 'react'
import { BackHandler, Animated, Easing } from 'react-native'
import {
  StackNavigator,
  TabNavigator,
  TabBarBottom,
  addNavigationHelpers,
  NavigationActions,
} from 'react-navigation'

import {
  initializeListeners,
  createReduxBoundAddListener,
  createReactNavigationReduxMiddleware,
} from 'react-navigation-redux-helpers'

import { connect } from 'react-redux'

import Login from './containers/Login'
import Forecast from './containers/forecast/Forecast'
import Detail from './containers/Detail'
import Home from './containers/home/Home'
import Statistics from './containers/statistics/Statistics'
import Consultant from './containers/consultant/Consultant'
import News from './containers/news/News'

import { AssetLiabilityStack,ProfitStack, CashFlowStack,RateAnalyzeStack,RateAnalyzeCommonStack } from './containers/home/HomeStack'
import { NewsStack } from './containers/news/NewsStack'
import { ConsultantStack, MessageStack } from './containers/consultant/ConsultantStack'
import { ForecastStack, TzYcResultStack } from './containers/forecast/ForecastStack'


import TabBarItem from './widgets/TabBarItem'

const HomeNavigator = TabNavigator(
  {
    Home: {
      screen: Statistics,
      navigationOptions: {
        tabBarLabel: '报告',
        tabBarIcon: ({ focused, tintColor }) => (
          <TabBarItem
            tintColor={tintColor}
            focused={focused}
            normalImage={require('./images/tabbar/home.png')}
            selectedImage={require('./images/tabbar/home_selected.png')}
          />
        ),
      },
    },
    Statistics: {
      screen: Home,
      navigationOptions: {
        tabBarLabel: '分析',
        tabBarIcon: ({ focused, tintColor }) => (
          <TabBarItem
            tintColor={tintColor}
            focused={focused}
            normalImage={require('./images/tabbar/statistics.png')}
            selectedImage={require('./images/tabbar/statistics_selected.png')}
          />
        ),
      },
    },
    Consultant: {
      screen: Consultant,
      navigationOptions: {
        tabBarLabel: '在线顾问',
        tabBarIcon: ({ focused, tintColor }) => (
          <TabBarItem
            tintColor={tintColor}
            focused={focused}
            normalImage={require('./images/tabbar/consultant.png')}
            selectedImage={require('./images/tabbar/consultant_selected.png')}
          />
        ),
      },
    },
    Forecast: {
      screen: Forecast,
      navigationOptions: {
        tabBarLabel: '预测',
        tabBarIcon: ({ focused, tintColor }) => (
          <TabBarItem
            tintColor={tintColor}
            focused={focused}
            normalImage={require('./images/tabbar/forecast.png')}
            selectedImage={require('./images/tabbar/forecast_selected.png')}
          />
        ),
      },
    },
    News: {
      screen: News,
      navigationOptions: {
        tabBarLabel: '资讯',
        tabBarIcon: ({ focused, tintColor }) => (
          <TabBarItem
            tintColor={tintColor}
            focused={focused}
            normalImage={require('./images/tabbar/news.png')}
            selectedImage={require('./images/tabbar/news_selected.png')}
          />
        ),
      },
    },
  },
  {
    tabBarComponent: TabBarBottom,
    tabBarPosition: 'bottom',
    swipeEnabled: false,
    animationEnabled: false,
    lazyLoad: true,
    lazy: true,
  }
)

const MainNavigator = StackNavigator(
  {
    HomeNavigator: { screen: HomeNavigator },
    Detail: { screen: Detail },
  },
  {
    headerMode: 'float',
  }
)

const AppNavigator = StackNavigator(
  {
    Login: { screen: Login },
    Main: { screen: MainNavigator },
    AssetLiabilityStack: { screen: AssetLiabilityStack},
    ProfitStack: {screen: ProfitStack},
    CashFlowStack: { screen: CashFlowStack},
    RateAnalyzeCommonStack: { screen: RateAnalyzeCommonStack },
    NewsStack: {screen: NewsStack},
    ConsultantStack: { screen: ConsultantStack},
    ForecastStack: {screen: ForecastStack},
    MessageStack: {screen: MessageStack},
    RateAnalyzeStack: { screen: RateAnalyzeStack},
    TzYcResultStack: {screen: TzYcResultStack},
  },
  {
    headerMode: 'none',
    mode: 'modal',
    navigationOptions: {
      gesturesEnabled: false,
    },
    transitionConfig: () => ({
      transitionSpec: {
        duration: 300,
        easing: Easing.out(Easing.poly(4)),
        timing: Animated.timing,
      },
      screenInterpolator: sceneProps => {
        const { layout, position, scene } = sceneProps
        const { index } = scene

        const height = layout.initHeight
        const translateY = position.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [height, 0, 0],
        })

        const opacity = position.interpolate({
          inputRange: [index - 1, index - 0.99, index],
          outputRange: [0, 1, 1],
        })

        return { opacity, transform: [{ translateY }] }
      },
    }),
  }
)


function getCurrentScreen(navigationState) {
  if (!navigationState) {
    return null
  }
  const route = navigationState.routes[navigationState.index]
  if (route.routes) {
    return getCurrentScreen(route)
  }
  return route.routeName
}

export const routerMiddleware = createReactNavigationReduxMiddleware(
  'root',
  state => state.router
)
const addListener = createReduxBoundAddListener('root')

@connect(({ app, router }) => ({ app, router }))
class Router extends PureComponent {
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backHandle)
  }

  componentDidMount() {
    initializeListeners('root', this.props.router)
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandle)
  }

  backHandle = () => {
    const currentScreen = getCurrentScreen(this.props.router)
    if (currentScreen === 'Login') {
      return true
    }
    if (currentScreen !== 'Home') {
      this.props.dispatch(NavigationActions.back())
      return true
    }
    return false
  }

  render() {
    const { dispatch, app, router } = this.props

    const navigation = addNavigationHelpers({
      dispatch,
      state: router,
      addListener,
    })
    return <AppNavigator navigation={navigation} />
  }
}

export function routerReducer(state, action = {}) {
  return AppNavigator.router.getStateForAction(action, state)
}

export default Router
